from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from schemas.translation import TranslationRequest, TranslationResponse, TranslationHistoryCreate
from services.translation_service import translate_service
from api.routes.auth import get_current_user
from models.user import User
from models.translation_history import TranslationHistory
from db import get_db
import asyncio

router = APIRouter()

@router.post("/translate", response_model=TranslationResponse)
async def translate_text(
    request: TranslationRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    翻译文本
    """
    try:
        # 调用翻译服务
        translated_text, error = await translate_service.translate(
            request.text, 
            request.from_lang, 
            request.to_lang
        )
        
        if error:
            return TranslationResponse(
                success=False,
                error_message=error,
                from_lang=request.from_lang,
                to_lang=request.to_lang,
                original_text=request.text
            )
        
        # 保存翻译历史到数据库
        try:
            print(f"保存翻译历史: 用户ID={current_user.id}, 文本={request.text[:50]}...")
            history_item = TranslationHistory(
                user_id=current_user.id,
                source_text=request.text,
                translated_text=translated_text,
                source_lang=request.from_lang,
                target_lang=request.to_lang
            )
            db.add(history_item)
            db.commit()
            print("翻译历史保存成功")
        except Exception as e:
            # 翻译历史保存失败不影响翻译结果
            print(f"保存翻译历史失败: {e}")
            import traceback
            traceback.print_exc()
        
        return TranslationResponse(
            success=True,
            translated_text=translated_text,
            from_lang=request.from_lang,
            to_lang=request.to_lang,
            original_text=request.text
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"翻译服务异常: {str(e)}"
        )

@router.get("/languages")
async def get_supported_languages():
    """
    获取支持的语言列表
    """
    languages = [
        {"code": "zh", "name": "中文"},
        {"code": "en", "name": "英语"},
        {"code": "yue", "name": "粤语"},
        {"code": "wyw", "name": "文言文"},
        {"code": "jp", "name": "日语"},
        {"code": "kor", "name": "韩语"},
        {"code": "fra", "name": "法语"},
        {"code": "spa", "name": "西班牙语"},
        {"code": "th", "name": "泰语"},
        {"code": "ara", "name": "阿拉伯语"},
        {"code": "ru", "name": "俄语"},
        {"code": "pt", "name": "葡萄牙语"},
        {"code": "de", "name": "德语"},
        {"code": "it", "name": "意大利语"},
        {"code": "el", "name": "希腊语"},
        {"code": "nl", "name": "荷兰语"},
        {"code": "pl", "name": "波兰语"},
        {"code": "bul", "name": "保加利亚语"},
        {"code": "est", "name": "爱沙尼亚语"},
        {"code": "dan", "name": "丹麦语"},
        {"code": "fin", "name": "芬兰语"},
        {"code": "cs", "name": "捷克语"},
        {"code": "rom", "name": "罗马尼亚语"},
        {"code": "slo", "name": "斯洛文尼亚语"},
        {"code": "swe", "name": "瑞典语"},
        {"code": "hu", "name": "匈牙利语"},
        {"code": "cht", "name": "繁体中文"},
        {"code": "vie", "name": "越南语"},
        {"code": "lao", "name": "老挝语"},
        {"code": "mya", "name": "缅甸语"},
        {"code": "lisu", "name": "傈僳语（自动检测）"},
    ]
    
    return {"languages": languages}



